package com.voxel.sense.infomsg.module.firm.details.history;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.view.EmptyView;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.module.common.VRecyclerFrag;
import com.voxel.sense.infomsg.view.decoration.ItemDivider;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.api.BaseEntity;

/**
 * Created by ChenYiYao on 2018/7/26.
 */
public class HistoryDataFrag extends VRecyclerFrag<HistoryDataContract.Presenter, BaseEntity>
        implements HistoryDataContract.View<BaseEntity> {
    @BindView(R.id.recycle_view)
    RecyclerView recycle_view;
    @BindView(R.id.tv_empty)
    TextView tv_empty;
    @BindView(R.id.tv_start_time)
    TextView tv_start_time;
    @BindView(R.id.tv_end_time)
    TextView tv_end_time;
    @BindView(R.id.btn_search)
    Button btn_search;
    @BindView(R.id.empty_view)
    EmptyView empty_view;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.appbar)
    AppBarLayout appbar;

    private RecyclerAdapter mAdapter;
    private String mSId;
    private TimePickerView pvTime;//时间选择器

    @Override
    protected HistoryDataContract.Presenter initPresenter() {
        return new HistoryPresenter(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.layout_firm_history;
    }

    @Override
    public void onDestroy() {
        mPresenter.destroy();
        super.onDestroy();
    }

    @Override
    protected void initArgs(Bundle bundle) {
        super.initArgs(bundle);
        if (bundle == null)
            return;
        mSId = bundle.getString(IntentConstants.STRING_TYPE);
    }

    @Override
    protected void initData() {
        super.initData();
        //初始化recycle
        empty_view.bind(refresh_layout);
        recycle_view.setLayoutManager(new LinearLayoutManager(getContext()));
        recycle_view.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider_1dp_white));
        mAdapter = new HistoryRecycleAdapter();
        recycle_view.setAdapter(mAdapter);

        //初始化默认查询时间
        Date startOfDay = TimeUtils.getStartOfDay(TimeUtils.getNowDate());
        tv_start_time.setText(TimeUtils.date2String(startOfDay, new SimpleDateFormat(Constants.TimeYMDHFormat)));
        tv_end_time.setText(TimeUtils.getNowString(new SimpleDateFormat(Constants.TimeYMDHFormat)));

        //默认加载当天数据
        onPreRefreshData("", "");
        //初始化时间选择器
        initTimeSelectView();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                String start = tv_start_time.getText().toString();
                String end = tv_end_time.getText().toString();
                //拉起刷新
                mPresenter.doRefresh(mSId, start, end);
            }
        });
    }

    private void onPreRefreshData(String start, String end) {
        empty_view.triggerOk();
        onRefresh();
    }

    @Override
    public RecyclerAdapter<BaseEntity> getRecyclerViewAdapter() {
        return mAdapter;
    }

    @Override
    public void onRefreshFinish() {
        super.onRefreshFinish();
        //由于该界面不提供下拉刷新功能，但刷新结束后，应当设置下拉刷新不可用，当需要刷新时再放开
        refresh_layout.setEnableRefresh(false);
        //有可能在刷新的时候，滑动隐藏AppBarLayout，若这时显示空界面。AppBarLayout则无法再通过滑动显示。这时需强制显示
        //改变代码就是强行回到初始位置
        CoordinatorLayout.Behavior coordbehavior = ((CoordinatorLayout.LayoutParams) appbar.getLayoutParams()).getBehavior();
        if (mAdapter.getItemCount() <= 0 && coordbehavior instanceof AppBarLayout.Behavior) {
            AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) coordbehavior;
            int topAndBottomOffset = behavior.getTopAndBottomOffset();
            if (topAndBottomOffset != 0) {
                behavior.setTopAndBottomOffset(0);

            }
        }
    }


    @Override
    public void onRefresh() {
        refresh_layout.setEnableRefresh(true);//若false，无法拉起刷新头控件
        refresh_layout.autoRefresh();
    }


    @OnClick({R.id.btn_search, R.id.tv_start_time, R.id.tv_end_time})
    void onClickEvnet(View view) {
        switch (view.getId()) {
            case R.id.tv_start_time:
                pvTime.show(tv_start_time);
                break;
            case R.id.tv_end_time:
                String starTime = tv_start_time.getText().toString();
                if (TextUtils.isEmpty(starTime)) {
                    super.showError("请先选择开始时间");
                    return;
                }

                //初始选择时间
                //若选择过时间，则从已选中的时间为选择起点
                //否则是开始时间的下一个小时
                Calendar calendar = Calendar.getInstance();
                String endText = tv_end_time.getText().toString();
                if (!TextUtils.isEmpty(endText)) {
                    long millis = TimeUtils.string2Millis(endText, new SimpleDateFormat(Constants.TimeYMDHFormat));
                    calendar.setTimeInMillis(millis);
                } else {
                    long millis = TimeUtils.string2Millis(starTime, new SimpleDateFormat(Constants.TimeYMDHFormat));
                    calendar.setTimeInMillis(millis);
                    calendar.add(Calendar.HOUR, 1);
                }
                pvTime.setDate(calendar);
                pvTime.show(tv_end_time);
                break;
            case R.id.btn_search:
                //搜索按钮点击事件
                String start = tv_start_time.getText().toString();
                String end = tv_end_time.getText().toString();
                onPreRefreshData(start, end);
                break;
        }
    }


    /**
     * 初始化时间选择器
     */
    private void initTimeSelectView() {
        //初始化时间选择器的开始及结束时间
//        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        //正确设置方式 原因：注意事项有说明
        startDate.set(Calendar.DATE, 1);
        startDate.set(Calendar.MONTH, 0);
        Calendar endDate = Calendar.getInstance();
        buildTimePicker(startDate, endDate);
    }

    /**
     * 创建时间选择器
     *
     * @param selectedDate 选择器的起始时间
     * @param endDate      选择器的终止时间
     */
    private void buildTimePicker(Calendar selectedDate, Calendar endDate) {

        pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                onCoverTime(date, v);
            }
        })
                .setType(new boolean[]{true, true, true, true, false, false})//分别表示是否显示年，月，日，时，分，秒，默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentTextSize(16)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(selectedDate, endDate)//起始终止年月日设定
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();

    }

    private void onCoverTime(Date date, View v) {
//        转换时间格式
        String string = TimeUtils.date2String(date, new SimpleDateFormat(Constants.TimeYMDHFormat));
        if (v.getId() == R.id.tv_start_time) {
            tv_start_time.setText(string);
        } else if (v.getId() == R.id.tv_end_time) {
            tv_end_time.setText(string);
        }
    }

}
